<template>
	<!-- 外勤 -->
	<div class="app-container">
		<!-- 使用搜索组件 -->
		<searchOption id="searchForm" ref="searchUnit" type="outSideTask" :total="total" :status="queryParams.status"
			@searchList="parentSearchList"></searchOption>

		<vxe-table border ref="xTable" show-overflow :data="infoList" :column-config="{ resizable: false }"
			:edit-config="{ trigger: 'click', mode: 'cell' }" @scroll="srcollFn" :height="autoTableHeight">
			<vxe-column title="" width="800" fixed="left">
				<vxe-column field="customName" title="公司名称" :edit-render="{}" width="230">
					<template #edit="{ row }">
						<vxe-input v-model="row.customName" type="text" placeholder="请输入公司名称" @blur="nameChangeEvent({ row })">
						</vxe-input>
					</template>
				</vxe-column>
				<vxe-column field="customNumber" title="公司证号" :edit-render="{}" width="150">
					<template #edit="{ row }">
						<vxe-input v-model="row.customNumber" type="text" placeholder="请输入公司证号" @blur="nameChangeEvent({ row })">
						</vxe-input>
					</template>
				</vxe-column>

				<vxe-column field="handleContent" title="业务描述" width="70">
					<template #default="{ row }">
						<el-popover placement="top" width="100%" v-if="row.taskId !== null" trigger="hover"
							@show="popoverImg(row, 2)">
							<span slot="reference" style="color: #1890ff;">查看描述</span>
							<img v-if="imageSrc !== ''" :src="imageSrc" style="width: 500px" />
						</el-popover>
					</template>
				</vxe-column>
				<vxe-column field="customManager" title="经理" :edit-render="{}" width="62">
					<template #edit="{ row }">
						<vxe-input v-model="row.customManager" type="text" placeholder="请输入销售经理" @blur="nameChangeEvent({ row })">
						</vxe-input>
					</template>
				</vxe-column>

				<vxe-column field="region" title="所属区域" :edit-render="{}" width="62">
					<template #edit="{ row }">
						<vxe-input v-model="row.region" type="text" placeholder="请输入所属区域" @blur="nameChangeEvent({ row })">
						</vxe-input>
					</template>
				</vxe-column>
			</vxe-column>

			<vxe-column field="legalName" title="法人" :edit-render="{}" width="62">
				<template #edit="{ row }">
					<vxe-input v-model="row.legalName" type="text" placeholder="请输入法人姓名" @blur="nameChangeEvent({ row })">
					</vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="legalPersonNumber" title="法人身份证" :edit-render="{}" width="145">
				<template #edit="{ row }">
					<vxe-input v-model="row.legalPersonNumber" type="text" placeholder="请输入法人身份证"
						@blur="nameChangeEvent({ row })"></vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="legalPersonPhone" title="法人电话" :edit-render="{ autofocus: '.vxe-input&#45;&#45;inner' }"
				width="100">
				<template #edit="{ row }">
					<vxe-input v-model="row.legalPersonPhone" type="text" @blur="nameChangeEvent({ row })"></vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="callPhone" title="联系人电话" :edit-render="{ autofocus: '.vxe-input&#45;&#45;inner' }" width="100">
				<template #edit="{ row }">
					<vxe-input v-model="row.callPhone" type="text" @blur="nameChangeEvent({ row })"></vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="gmtCreate" title="任务描述" width="120">
				<template #edit="{ row }">
					<vxe-input v-model="row.gmtCreate" type="text" placeholder="请输入任务描述" transfer></vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="gmtCreate" title="回执上传" width="120">
				<template #edit="{ row }">
					<vxe-input v-model="row.gmtCreate" type="text" placeholder="请输入任务描述" transfer></vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="gmtCreate" title="完成描述" width="120">
				<template #edit="{ row }">
					<vxe-input v-model="row.gmtCreate" type="text" placeholder="请输入任务描述" transfer></vxe-input>
				</template>
			</vxe-column>

			<vxe-column title="操作" width="300">
				<template #default="{ row }">
					<el-button v-if="row.taskStatus != 5 && row.taskStatus !== 3" size="mini" type="text" icon="el-icon-s-claim"
						@click="completedTask(row, 1)">任务完成
					</el-button>
					<el-button v-if="row.taskStatus != 5 && row.taskStatus !== 3" size="mini" type="text" icon="el-icon-s-release"
						@click="completedTask(row, 2)">任务失败
					</el-button>
				</template>
			</vxe-column>
		</vxe-table>

		<el-dialog ref="previewPdf" :visible.sync="uploadImgVis" :modal="true" width="40%" title="图片上传" append-to-body>
			<div v-if="imageSrc !== ''">
				<img :src="imageSrc" style="width: 60%; height: 20%" height="30%" />
				<div style="line-height: 50px">
					您可通过下方上传控件进行重新上传该图片
				</div>
			</div>

			<div v-else>您没有之前上传的照片可预览</div>
			<el-upload class="upload-demo" drag :action="uploadImgUrl" :headers="headers" :on-success="successAction"
				:data="{ customId: this.customId, type: this.uploadKey }" :show-file-list="false" accept=".jpeg,.jpg,.png">
				<i class="el-icon-upload"></i>
				<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
				<div class="el-upload__tip" slot="tip">只能上传jpg/png文件</div>
			</el-upload>
		</el-dialog>

		<!-- 添加或修改客户信息对话框 -->
		<el-dialog ref="previewPdf" :visible.sync="viewImgVis" :modal="true" width="50%" height="50%" title="图片查看"
			append-to-body>
			<img :src="imageSrc" style="width: 100%; height: 50%" />
		</el-dialog>
	</div>
</template>

<script>
import {
	listInfo,
	getInfo,
	delInfo,
	addInfo,
	updateInfo,
	updateContractCustom,
	loadImage,
	previewImage,
	listOfContractType,
} from "@/api/system/info";

import { updateRemark, listRemark } from "@/api/system/remark";
import { pcaTextArr } from "element-china-area-data";
import second from "@/components/Crontab/second.vue";
import { getToken } from "@/utils/auth";
import { listUser } from "@/api/system/user";
import { updateTask } from "@/api/outsideTask/outSidetask";
import searchOption from "@/components/searchOption";

export default {
	name: "Info",
	dicts: [],
	components: {
		searchOption
	},
	data() {
		return {
			requeryFlag: true,
			pcaTextArr,
			autoTableHeight: 750,
			selectedOptions: [],
			remarkId: "",
			internalStaff: [],
			formRemark: {},
			openRecord: false,
			openContract: false,
			remarkList: [],
			checkList1: [],
			checkList2: [],
			checkList3: [],
			checkList4: [],
			checkList: [],
			statusList: [
				{ label: "未成交", value: "0" },
				// { label: '已成交', value: '1' },
				// { label: '注册中', value: '2' },
				// { label: '完毕', value: '3' },
				{ label: "废弃", value: "4" },
			],
			loading: true,

			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 客户信息表格数据
			infoList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			callPhone: "",
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 30,
				contractType: -1,
				taskType: 2,
				customName: null,
				legalName: null,
				customNumber: null,
				legalPersonNumber: null,
				source: null,
				province: null,
				city: null,
				region: null,
				adressDetail: null,
				bussLicenseImage: null,
				bussLicenseImageMinor: null,
				legalIdCardFront: null,
				legalIdCardBack: null,
				callPhone: null,
				callName: null,
				customManager: null,
				gmtCreate: null,
				successTime: null,
				status: 3,
				degree: null,
			},
			// 表单参数
			form: {
				groupDate: [],
				contractAmount: 0,
				secondAmount: null,
				contractType: 0,
				regionArea: null,
				regionAreaArry: [],
				bussionRegister: null,
				bussionRegisterVo: [],
				registerAllAmount: null,
				registerAllNotes: null,
				registerWorker: null,
				registerBankOpen: null,
				bussionEntrust: null,
				bussionEntrustVo: [],
				entrustIndividualAmount: null,
				entrustIndividualNotes: null,
				entrustVerificationAmount: null,
				entrustVerificationNotes: null,
				entrustSmallAmount: null,
				entrustSmallNotes: null,
				entrustGeneralAmount: null,
				entrustGeneralNotes: null,
				entrustInvoiceAmount: null,
				entrustInvoiceNotes: null,
				entrustSocialAmount: null,
				entrustSocialNotes: null,
				entrustAccumulationAmount: null,
				entrustAccumulationNotes: null,
				entrustAddressAmount: null,
				entrustAddressNotes: null,
				entrustCycleStrat: null,
				entrustCycleEnd: null,
				bussionChange: null,
				bussionChangeVo: [],
				changeAmount: null,
				changeNotes: null,
				changeOtherNotes: null,
				bussionCancel: null,
				bussionCancelVo: [],
				cancelAmount: null,
				cancelNotes: null,
				cancelOtherNotes: null,
				bussionClientele: null,
				bussionClienteleVo: [],
				clienteleAmount: null,
				clienteleNotes: null,
				clienteleOtherNotes: null,
				contractRenewAmount: null,
				contractNotes: null,
				contractPhase: null,
			},
			queryEmp: {
				pageNum: 1,
				pageSize: 30,
				deptId: 200,
			},
			dateRange: [],
			breadList: [], //初始化
			// 表单校验
			rules: {},
			rowId: "",

			uploadImgUrl:
				process.env.VUE_APP_BASE_API + "/custom/info/uploadContract",
			headers: {
				Authorization: "Bearer " + getToken(),
			},

			uploadImgVis: false,
			viewImgVis: false,
			imageSrc: "",
			customId: "",
			uploadKey: "",
			popoverVis: false,
			hoverId: "",
			keyIsList: [
				{ label: "是", value: 1 },
				{ label: "否", value: 0 },
			],
		};
	},
	created() {
		// this.getList();
		// this.listUser();
	},
	watch: {
		// 监听路由对象中的变化
		'$route': {
			handler: function (from, to) {
				// 当路由发生变化时会调用这个函数
				this.infoList = [];
				this.queryParams.pageNum = 1;
				this.queryParams.pageSize = 30;
				this.queryParams.contractType = from.query.contractType;
				this.queryParams.status = from.query.status;
				this.queryParams.taskType = from.query.taskType;
				this.getList();
			},
			// 如果需要在路由变化时立即响应，可以设置immediate为true
			immediate: true
		}
	},
	computed: {
		second() {
			return second;
		},
	},
	mounted() {
		this.$nextTick(() => {
			// 视口高度 - 列表上方的元素高度
			let allHeight = window.innerHeight;
			let element = [
				document.getElementById('navbar'),
				document.getElementById('searchForm'),
				document.getElementById('tags-view-container'),
			]
			let domHeight = element.map(item => item.offsetHeight)
			// let tableHeight = allHeight - 50 - 34 - 50 - 36;
			let tableHeight = allHeight - 40 - domHeight[0] - domHeight[1] - domHeight[2];
			this.autoTableHeight = tableHeight;
		})
	},
	methods: {
		// 搜索子组件触发搜索
		parentSearchList(data) {
			this.queryParams.pageNum = data.pageNum;
			this.queryParams.pageSize = data.pageSize;
			this.queryParams.callName = data.callName;
			this.queryParams.callPhone = data.callPhone;
			this.queryParams.customName = data.customName;
			this.queryParams.contractType = data.contractType !== null && data.contractType !== "" ?
				data.contractType : this.queryParams.contractType;
			this.queryParams.customManager = data.customManager;
			this.handleQuery();
		},
		formatStatus(value) {
			if (value == "0") {
				return "未成交";
			}
			if (value == "1") {
				return "已成交";
			}
			if (value == "2") {
				return "注册中";
			}
			if (value == "3") {
				return "完毕";
			}
			if (value == "4") {
				return "废弃";
			}
			return "";
		},
		listUser() {
			listUser(this.addDateRange(this.queryEmp, this.dateRange)).then(
				(response) => {
					this.internalStaff = response.rows;
				}
			);
		},
		/** 查询客户信息列表 */
		getList() {
			this.loading = true;
			this.queryParams.pageNum = 1;
			listOfContractType(this.queryParams).then((response) => {
				this.infoList = response.rows;
				this.total = response.total;
				this.loading = false;
			});
		},
		nameChangeEvent({ row }) {
			let form = row;
			// console.log(form.status)
			updateContractCustom(form).then((response) => {
				// this.getList();
			});
		},

		// 取消按钮
		cancel() {
			this.open = false;
		},
		// 取消按钮
		cancelContract() {
			this.openContract = false;
			this.reset();
		},
		// 表单重置
		reset() {
			this.form = {
				id: null,
				customName: null,
				legalName: null,
				customNumber: null,
				legalPersonNumber: null,
				source: null,
				province: null,
				city: null,
				region: null,
				adressDetail: null,
				bussLicenseImage: null,
				bussLicenseImageMinor: null,
				legalIdCardFront: null,
				legalIdCardBack: null,
				callPhone: null,
				callName: null,
				customManager: null,
				gmtCreate: null,
				successTime: null,
				status: null,
			};
			this.resetForm("form");
		},
		talkBackHistory(row) {
			this.openRecord = true;
			let customId = row.id;
			let queryParams = {
				pageNum: 1,
				pageSize: 30,
			};
			if (customId) {
				queryParams.customId = customId;
			}
			console.log("customId", customId);
			listRemark(queryParams).then((response) => {
				this.remarkList = response.rows;
			});
		},
		createContract(row) {
			// this.form = {}
			// this.checkList = []
			// this.checkList1 = []
			// this.checkList2 = []
			// this.checkList3 = []
			// this.checkList4 = []
			this.openContract = true;
			this.rowId = row.id;
		},

		srcollFn(e) {
			let circulateNum = this.total / 30;
			let bottomOffset = e.scrollHeight - e.scrollTop - e.bodyHeight;
			if (bottomOffset < 50 && this.queryParams.pageNum < circulateNum) {
				if (this.requeryFlag) {
					this.requeryFlag = false;
					this.loading = true;
					this.queryParams.pageNum++;
					const h = this.$createElement;
					listOfContractType(this.queryParams).then((response) => {
						this.infoList = [...this.infoList, ...response.rows];
						// this.total = response.total;
						this.loading = false;
						this.requeryFlag = true;
					});
				}
			}
		},

		//上传图片等
		uploadTableImg(row, key) {
			this.uploadImgVis = true;
			this.uploadKey = key;
			this.customId = row.row.contractId;
			this.successAction();
		},

		//上传图片成功
		successAction() {
			this.getList();
			this.imageSrc = "";
			loadImage(this.customId, this.uploadKey).then((response) => {
				if (response.type === "image/jpg") {
					const blobData = {};
					blobData.type = "application/image;chartset=UTF-8";
					this.imageSrc = window.URL.createObjectURL(
						new Blob([response], blobData)
					);
				}
			});
		},

		//hover popover fc
		popoverFc(row, key) {
			this.uploadKey = key;
			this.customId = row.row.id;
			this.successAction();
		},
		formatKeyIs(value) {
			if (value === 1) {
				return "是";
			}
			if (value === 0) {
				return "否";
			}
		},
		completedTask(row, num) {
			let params = {
				id: row.taskDetailId,
				status: 1,
				failReason: undefined,
			};
			if (num === 1) {
				params.status = 1;
				updateTask(params).then((response) => {
					console.log(response);
					if (response.code === 200) {
					}
				});
			} else {
				this.$prompt("请输入任务失败原因", "原因", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
				})
					.then(({ value }) => {
						params.status = 2;
						params.failReason = value;
						updateTask(params).then((response) => {
							console.log(response);
							if (response.code === 200) {
							}
						});
					})
					.catch(() => {
						this.$message({
							type: "info",
							message: "取消输入",
						});
					});
			}
			this.getList();
		} /** 搜索按钮操作 */,
		handleQuery() {
			this.queryParams.pageNum = 1;
			this.getList();
		} /** 重置按钮操作 */,
		resetQuery() {
			this.resetForm("queryForm");
			this.handleQuery();
		},
		// 业务描述 查看图片
		popoverImg(row) {
			let url = '';
			url = `/task/${row.contractId}.png`;
			this.imageSrc = "";
			previewImage(url).then((response) => {
				if (response.type === "image/jpg") {
					const blobData = {};
					blobData.type = "application/image;chartset=UTF-8";
					this.imageSrc = window.URL.createObjectURL(
						new Blob([response], blobData)
					);
				}
			});
		},
	},
};
</script>

<style scoped>
.el-row {
	margin-bottom: 20px;
}

.newTree /deep/ .el-tree-node__content {
	height: 40px !important;
}

.newdialog .el-row {
	margin-bottom: 0px !important;
}

.width18 {
	width: 180px;
}
</style>